package com.yixun.qfbao.api.service.impl;

import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.qfbao.api.service.SmsHistoryApiService;
import com.yixun.qfbao.apidto.MarketingSmsAsyncReqDto;
import com.yixun.qfbao.apidto.MarketingSmsAsyncResDto;
import com.yixun.qfbao.apidto.SmsReportPageReqDto;
import com.yixun.qfbao.apidto.SmsReportPageResDto;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.SmsHistory;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.model.enums.SMSPlatformEnum;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.SmsHistoryService;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SmsHistoryApiServiceImpl implements SmsHistoryApiService {
    private Logger logger = LoggerFactory.getLogger(SmsHistoryApiServiceImpl.class);
    @Autowired
    private SmsHistoryService smsHistoryService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SMSUtil smsUtil;
    @Override
    public SmsReportPageResDto getSmsReportPage(SmsReportPageReqDto reqDto) {
        SmsReportPageResDto resDto = new SmsReportPageResDto();
        //获取公司信息
        CompanyDto companyDto = new CompanyDto();
        if(StringUtils.isNotEmpty(reqDto.getCompanyUuid())){
            companyDto.setCompanyUuid(reqDto.getCompanyUuid());
        }else if(StringUtils.isNotEmpty(reqDto.getDomain())){
            companyDto.setDomain(reqDto.getDomain());
        }else{
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("未获取到渠道商信息");
            return resDto;
        }
        Company company = companyService.selectByDto(companyDto);
        if(company == null){
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("未获取到渠道商信息");
            return resDto;
        }

        SmsHistoryDto smsHistory = new SmsHistoryDto();
        smsHistory.setCreateTimeBefore(reqDto.getBeginDate());
        smsHistory.setCreateTimeAfter(reqDto.getEndDate());
        smsHistory.setMerchantId(company.getId());
        smsHistory.setSendStatus(SendStatusEnum.SUCCESS.getNo());
        smsHistory.setOrders(" t.create_time desc ");
        Page<SmsHistory> pageModel = smsHistoryService.getPageModel(smsHistory, PageUtil.begin(reqDto.getPageNo(),reqDto.getPageSize()),reqDto.getPageSize());
        pageModel.setPageNumber(reqDto.getPageNo());
        resDto.setPage(pageModel);
        return resDto;
    }

    //电话平台回调信息
    @Override
    public MarketingSmsAsyncResDto marketingSmsAsync(MarketingSmsAsyncReqDto reqDto){
        //异步回调之后查看状态，如果短信发送失败，进行补发，并将状态或次数加1
        MarketingSmsAsyncResDto resDto = new MarketingSmsAsyncResDto();
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        if(reqDto.getSendStatus().equals("0")){
            //短信发送失败
            /**
             * 获取失败短信发送记录
             * 仅限当天
             */
            List<SmsHistory> shList = new ArrayList<>();
            SmsHistoryDto shDto = new SmsHistoryDto();
//            shDto.setSendStatus(SendStatusEnum.FAILURE.getNo());
            //uuid
            shDto.setOrderUuid(reqDto.getOrderUuid());
            int currRepeatCount = 0;
            try {
                shList = smsHistoryService.selectListByDto(shDto);
                if(null != shList && shList.size() > 0){
                    SmsHistory sh =shList.get(0);

                    LocalDate today = LocalDate.now();
                    LocalDateTime todayBefor = LocalDateTime.of(today, LocalTime.of(0,0,0));
                    LocalDateTime todayAfter = LocalDateTime.of(today, LocalTime.of(23,59,59));
                    Date todayBeforDate = Date.from(todayBefor.atZone(ZoneId.systemDefault()).toInstant());
                    Date todayAfterDate = Date.from(todayAfter.atZone(ZoneId.systemDefault()).toInstant());

                    SmsHistoryDto smsHistoryDto = new SmsHistoryDto();
                    smsHistoryDto.setReceiver(sh.getReceiver());
                    smsHistoryDto.setCreateTimeBefore(todayBeforDate);
                    smsHistoryDto.setCreateTimeAfter(todayAfterDate);
                    smsHistoryDto.setRepeatStatus(SendStatusEnum.SUCCESS.getNo());
                    smsHistoryDto.setExtendSql(" original_id is not null");
                    int countToday = smsHistoryService.selectCountByDto(smsHistoryDto);
                    if(countToday >= 30){
                        updateSmsHis(sh.getId(),reqDto.getReason()+"(今天重发次数已达"+countToday+"次，拒绝重发，人工干预)",SendStatusEnum.SUCCESS.getNo(),null);
                        return null;
                    }


                    //1.使用第一信息发送短信
                    //發送短信.采用第一信息的通道进行补发
                    //原因: 没有好用的且有钱的通道.
                    Map<String, Object> returnMap = smsUtil.sendMessage(sh.getContent(), sh.getReceiver(), null, null, null);
                    boolean sendStatus = (Boolean) returnMap.get("sendStatus");
                    String sendRes = String.valueOf(returnMap.get("sendRes"));

                    if(null != sh.getRepeatCount()){
                        currRepeatCount = Integer.parseInt(sh.getRepeatCount());
                    }
                    currRepeatCount +=1;

                    //保存短信历史信息
                    SmsHistoryDto smsHis = new SmsHistoryDto();
                    smsHis.setSender(smsUtil.getUserName());
                    smsHis.setSender("qiaofang");
                    smsHis.setReceiver(sh.getReceiver());
                    smsHis.setContent(sh.getContent());
                    smsHis.setSendStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
                    smsHis.setSendRes(sendRes);
                    smsHis.setOriginalId(sh.getId());
                    smsHis.setRepeatCount(String.valueOf(currRepeatCount));
                    smsHis.setMerchantId(sh.getMerchantId());
                    smsHis.setRemark(sh.getRemark());
                    smsHis.setCreateUserId(sh.getCreateUserId());
                    //添加平台信息
                    smsHis.setPlatform(SMSPlatformEnum.PLATFORM_ONE.getNo());
                    if(returnMap.containsKey("orderUuid")){
                        smsHis.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
                    }
                    if(returnMap.containsKey("platform")){
                        smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
                    }
                    smsHistoryService.create(smsHis);
                    //2.更新相应状态
                    //修改当前短信发送次数
                    String sendStatusVal = sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo();
                    updateSmsHis(sh.getId(),reqDto.getReason(),sendStatusVal,String.valueOf(currRepeatCount));

                }
            }catch (Exception e){
                logger.error("补发短信失败: {}", e);
                resDto.setResult(ResultEnum.FAIL.getNo());
            }
        }
        return resDto;
    }

    private int updateSmsHis(long smsHisId,String reason,String repeateStatus,String repeatCount) {
        SmsHistoryDto smsHis = new SmsHistoryDto();
        smsHis.setId(smsHisId);
        smsHis.setReason(reason);
        smsHis.setRepeatStatus(repeateStatus);
        smsHis.setRepeatCount(repeatCount);
        return smsHistoryService.update(smsHis);
    }
}
